/**Spring Security配置文件，主要用于配置UserDetailsService和具体的url保护规则
 * 1）定义登录用户信息，方法一：实现UserDetailsService接口；方法二：AuthenticationManagerBuilder 中定义
 * 2）定义受保护的url和方法的访问规则：1）使用Ant风格的路径匹配符和SpEl配置url的访问权限，
 *                               2）在方法上添加注解来控制其权限（@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
 * UserDetailService：InMemoryUserDetailsManager、JdbcUserDetailsManager
 * 用户认证流程：UsernamePasswordAuthenticationFilter#attemptAuthentication-> ProviderManager#authenticate-> DaoAuthenticationProvider#authenticate
 * 可用以自定义AuthenticationProvider的子类来自定义账户认证逻辑
 */
package com.example.demoauthserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

import javax.sql.DataSource;
import java.sql.Connection;

@Configuration
@EnableWebSecurity
@Order(2)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //用户信息Bean
    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        String finalPassword = bCryptPasswordEncoder.encode("12345");
//        System.out.println("finalpassword:"+finalPassword);

//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(User.withUsername("user_1").password(finalPassword).authorities("USER").build());
//        manager.createUser(User.withUsername("user_2").password(finalPassword).authorities("ADMIN").build());
//        return manager;

//        JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
//        manager.setDataSource(dataSource);
//
//        if (!manager.userExists("user_1")) {
//            manager.createUser(User.withUsername("user_1").password("12345").roles("USER").build());
//        }
//        if (!manager.userExists("user_2")) {
//            manager.createUser(User.withUsername("user_2").password("12345").roles("ADMIN").build());
//        }
//        return manager;

        return super.userDetailsService();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
    /*等效替代
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return  super.authenticationManagerBean();
    }    */


//    用户及角色定义，密码必须加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .passwordEncoder(new BCryptPasswordEncoder())
//                .withUser("user_1")
//                .password(new BCryptPasswordEncoder().encode("12345"))
//                .roles("USER")
//                .and()
//                .withUser("user_2")
//                .password(new BCryptPasswordEncoder().encode("56789"))
//                .roles("USER","ADMIN");



        JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
        manager.setDataSource(dataSource);
        if (manager.userExists("user_1"))  manager.deleteUser("user_1");
        if (manager.userExists("user_2"))  manager.deleteUser("user_2");

        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user_1")
                .password(new BCryptPasswordEncoder().encode("12345"))
                .roles("USER")
                .and()
                .withUser("user_2")
                .password(new BCryptPasswordEncoder().encode("56789"))
                .roles("ADMIN")
                .and()
                .usersByUsernameQuery("select username,password,enabled from users WHERE username=?")       //这是缺省查询语句，可以另外自定义
                .authoritiesByUsernameQuery("select username,authority from authorities where username=?"); //这是缺省查询语句，可以另外自定义
//                .authenticationProvider(myAuthenticationProvider())      自定用户义认证方法
    }

    //配置授权，走 Spring Security 过滤器链,适用于后端接口（尤其是登录接口），此时可以获得session中的用户登录信息
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    .requestMatchers()
                .antMatchers("/login")
                .antMatchers("/oauth/authorize")
                .and()
                .authorizeRequests()
                .antMatchers("/user").permitAll()
                .antMatchers("/oauth/**").permitAll()   //放行oauth下请求
                .anyRequest().authenticated()    //所有请求都要通过认证，要放在全部认证规则的最后面
                .and()
                .csrf().disable()
//                .formLogin()
//                .and()
                .httpBasic()   ;   //获取authorization_code时必须配置
    }

    //直接放行，不走 Spring Security 过滤器链,适用于前端静态资源放行
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/js/**","/index.html","/img/**","/fonts/**","/favicon.ico","/index.html");
    }

    //角色继承，实现：所有 user 能够访问的资源，admin 都能够访问
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
        return hierarchy;
    }
}

